/**
 * Created by chengming on 18/5/27.
 * version 1.0
 */
const BaseJsonAdapter = require('../base/BaseJsonAdapter');
const ArticleHrefAdapter = require('../ArticleHrefAdapter');
const iconv = require("iconv-lite");
const vm = require('vm');
const request = require('request-promise');
const logger = require('../../conf/logger');
const querystring = require("querystring")
const cheerio = require('cheerio');
const urlTool = require('url');
const urldecode = require('urlencode')
const superagent = require('superagent')
var browserMsg = {}
var set_cookie = []
/**
 * 港交所-上市公司公告
 * @type {module.Bjp2p}
 */
module.exports = class HKetMi extends ArticleHrefAdapter {


    async getPostParam(url, cookie = '') {
        return await new Promise((resolve, reject) => {
            superagent.get(url).set(browserMsg).redirects(0).end(function (err, response) {
                resolve(response.text)
            })
        })
    }

    async getLoginCookie(url, cookie = '') {
        return await new Promise((resolve, reject) => {
            superagent.post(url).set(browserMsg).redirects(0).end(function (err, response) {
                if (response.headers['set-cookie'] !== null && response.headers['set-cookie'] !== undefined) {
                    set_cookie = response.headers['set-cookie'];
                    resolve(response.headers['set-cookie'])
                } else if (err) {
                    console.log(err.message)
                    resolve();
                } else {
                    resolve(set_cookie);
                }
            })
            /* superagent.post(url).set(browserMsg).redirects(0).then(function(err,response){
                 if (response.headers['set-cookie'] !== null && response.headers['set-cookie'] !== undefined) {
                     resolve(response.headers['set-cookie'])
                 }
             }).catch(function(err){
                 resolve()
             })*/
        })
    }

    async getHtml(url, cookie = '') {
        let data = await new Promise((resolve, reject) => {
            superagent.get(url).set(browserMsg).set('Cookie', cookie).redirects(0).end(function (err, response) {
                console.log(response.text)
                console.log(response.headers)
                resolve(response.text)
                // if (response.headers['set-cookie'] !== null && response.headers['set-cookie'] !== undefined) {
                //   resolve(response.headers['set-cookie'])
                // }
            })
        })

        return data;
    }

    test(var1) {
        var var_str = '' + var1
        var var_arr = var_str.split('')
        var LastDig = var_arr.reverse()[0]
        var minDig = var_arr.sort()[0]
        var subvar1 = (2 * (var_arr[2])) + (var_arr[1] * 1)
        var subvar2 = (2 * var_arr[2]) + var_arr[1]
        var my_pow = Math.pow(((var_arr[0] * 1) + 2), var_arr[1])
        var x = (var1 * 3 + subvar1) * 1
        var y = Math.cos(Math.PI * subvar2)
        var answer = x * y
        answer -= my_pow * 1
        answer += (minDig * 1) - (LastDig * 1)
        answer = answer + subvar2
        return answer
    }

    async main() {
        let url = this.requestUrl;
        let html = await this.getHtml(url, '')
        console.log(html)
        return html;
    }

    async doRequest() {
        /*request.cookieEnabled=true;
        let jar = request.jar();
        let cookie = request.cookie("BotMitigationCookie_1969904701684545095=\"633740001530694368lT1iEJWkumyIIlZ+o8MJ12VjB3s=\"; BIGipServerpool_http_hketwww1_prod=2617354432.20480.0000; hket_display=\"{\\\\\"viewport\\\\\":\\\\\"797x956\\\\\",\\\\\"resolution\\\\\":\\\\\"1920x1080\\\\\"}\"; hket-plus-anonymous=d4a1ceb6-202f-49b6-9458880; JSESSIONID=8F2B96F3C44E1FB3F1DBF0929706279A; GVID=201807040456290BBBD7403CC91D4FDB4D7360E99A989D");
        let option = this.getRequestOptions();
        jar.setCookie(cookie,option.url);
        option.jar = jar;
        option['resolveWithFullResponse']=true;
        let data = await request(option);*/
        let data = await this.main();
        return data;
    }


    parseHtml(html, linkRule) {
        //将解析后的内容加载进解析器
        let $ = cheerio.load(html);
        let contents = [];
        let that = this;
        let rangeText = '';
        let encoding = this.encoding;
        $(this.linkRule).each(function () {

            let title = $(this).attr('title').trim();
            let href = '';
            if ($(this).is('a') && $(this).attr('href')) {
                href = urlTool.resolve(that.requestUrl, $(this).attr('href'));
            }

            if (title.length != 0 || href.length != 0) {
                contents.push({
                    title: title,
                    href: href
                });
                rangeText += title + href;
            }

        });

        return {
            rangeText: rangeText,
            contents: contents
        };
    }

    async execute(){
        logger.debug('开始执行抓取->'+this.pageName);
        /*if(this.pageSite == 'https://ambcrypto.com/category/news/') {
            await report(this.pageSite, this.pageTitle, '', '开始请求');
        }*/
        //获取请求结果
        let body = await this.doRequest();

        //根据指定encoding解析页面
        let decodeBody = body

        /*if(this.pageSite == 'https://ambcrypto.com/category/news/') {
            let startIndex = decodeBody.indexOf('<div class="mvp-blog-story-text left relative"');
            await report(this.pageSite, this.pageTitle, '', '请求结束,decodeBody: ' + decodeBody.substr(startIndex));
        }*/
        logger.debug(this.pageName+'抓取执行完毕,开始分析文本');

        if(decodeBody.length<5) {
            logger.warn(this.pageName+'抓取到的页面为空');
            if(this.isTest == false){
                await report(this.pageSite, this.pageTitle, '', '抓取到的页面为空');
            }
            return {
                code: 401,
                errMsg: '抓取到的页面为空'
            };
        }

        if(!this.linkRule || this.linkRule.length == 0){
            logger.warn(this.pageName+'没有链接抓取规则');
            if(this.isTest == false){
                await report(this.pageSite, this.pageTitle, '', '没有链接抓取规则');
            }
            return {
                code: 401,
                errMsg: '没有链接抓取规则'
            };
        }

        let contentBlock = this.parseHtml(decodeBody, this.linkRule);
        if(contentBlock.rangeText.length == 0) {
            logger.warn(this.pageName + ">>>" + this.linkRule + "此抓取规则下,无内容匹配，decodeBody：" + decodeBody);
            if (this.isTest == false) {
                await report(this.pageSite, this.pageTitle, '', this.linkRule + "此抓取规则下,无内容匹配, decodeBody: " + decodeBody);
            }
            return {
                code: 402,
                errMsg: this.linkRule + "此抓取规则下,无内容匹配" + decodeBody
            };
        } else {
            logger.info(this.pageName + ">>>>>>res: " + contentBlock.rangeText);
        }

        await super.postSocket(this.id, this.rangeMd5, contentBlock.rangeText, contentBlock.contents,  decodeBody, this.cates, this.pageTitle, this.sourceTime, this.channel,
            this.followLink, this.foreign, this.contentRule, this.linkUniqueBy);

        return await super.postFilterUnique(contentBlock.contents,
            this.cates,
            this.foreign,
            this.linkUniqueBy,
            this.followLink,
            this.sourceTime,
            this.pageTitle,
            this.titleRule,
            this.contentRule,
            this.channel);
    }


}
